package com.nchu.argument.sys.util;

import org.springframework.util.Assert;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Date;

/**
 * @author fujianjian
 * @project argument-sys
 * @date 2019/2/26 23:12
 */
public final class TimeHelper {

    private static final ZoneId ZONE_ID = ZoneId.systemDefault();


    public static Date convertStr2Date(String date) {
        Assert.notNull(date, "target date not null");
        LocalDate localdate = LocalDate.parse(date);
        Instant instant = localdate.atStartOfDay(ZONE_ID).toInstant();
        return Date.from(instant);
    }

    public static Date convertStr2Date(String date, String formatter) {
        Assert.notNull(date, "convert date not null");
        Assert.notNull(formatter, "convert formatter not null");
        DateTimeFormatter datetimeFormatter = DateTimeFormatter.ofPattern(formatter);
        LocalDateTime localDateTime = LocalDateTime.parse(date, datetimeFormatter);
        Instant instant = localDateTime.toInstant(ZoneOffset.UTC);
        return Date.from(instant);
    }

    /**
     * 日期转localDateTime
     *
     * @param date
     * @return
     */
    public static LocalDateTime convertDate2LocalDateTime(Date date) {
        Assert.notNull(date, "target convert date not null");
        Instant instant = date.toInstant();
        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZONE_ID);
        return localDateTime;
    }

    public static Integer getIntervalDays(Date beginDate, Date endDate) {
        Assert.notNull(beginDate, "begin date not null");
        Assert.notNull(endDate, "end date not null");
        LocalDateTime beginTime = convertDate2LocalDateTime(beginDate);
        LocalDateTime endTime = convertDate2LocalDateTime(endDate);

        long interval = ChronoUnit.DAYS.between(beginTime, endTime);
        return Math.toIntExact(interval);
    }
}
